package com.lvhx.springboot.springbatch.batch;

import com.lvhx.springboot.entity.batch.Acctbal;
import com.lvhx.springboot.entity.User;
import com.lvhx.springboot.mapper.batch.AcctbalMapper;
import com.lvhx.springboot.mapper.UserMapper;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import javax.sql.DataSource;
import java.util.concurrent.TimeUnit;

/**
 * @auther 吕宏旭
 * @date 2019/9/4 14:18
 */
//@Transactional(transactionManager = "transactionManager")
public class WriteTasklet implements Tasklet {

    private String message;

    public void setMessage(String message){
        this.message = message;
    }

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AcctbalMapper acctbalMapper;
    @Autowired
    private DataSource batchDataSource;

    @Override
    public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {

        User user = queryDatasource();

        queryBatchDatasource();

        System.out.println("123");
//        try {
//            TimeUnit.SECONDS.sleep(120);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }

        user.setCreateBy("WriteTasklet");
        userMapper.updateByPrimaryKeySelective(user);
        return RepeatStatus.FINISHED;
    }

    @Transactional(transactionManager = "batchTransactionManager")
    public void queryBatchDatasource(){

        Acctbal acctbal = acctbalMapper.selectByPrimaryKey("9999980901");
        System.out.println(acctbal);
    }

    @Transactional(transactionManager = "transactionManager")
    public User queryDatasource(){

        User user = userMapper.selectByPrimaryKey(1L);
        System.out.println(user.getName());
        return user;
    }

}
